﻿using System;
using System.IO;

namespace WeChatBotSDK.Services
{
    /// <summary>
    /// 实现微信 API 服务接口的具体类。
    /// </summary>
    public class WeChatApiService : IWeChatApiService, IQXApiService
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl;
        private string safekey="";
        public string SafeKey
        {
            get => safekey;
            set
            {
                safekey = value;
            }
        }

        // JsonSerializerOptions 配置
        JsonSerializerOptions options = new JsonSerializerOptions
        {
            //WriteIndented = true, // 格式化 JSON 输出
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 禁止转义中文字符
        };

        /// <summary>
        /// 初始化 WeChatApiService 的实例。
        /// </summary>
        /// <param name="baseUrl">微信 API 的基础 URL。</param>
        public WeChatApiService(string baseUrl)
        {
            _baseUrl = baseUrl.TrimEnd('/');
            _httpClient = new HttpClient();
           
        }
        /// <inheritdoc/>
        public async Task<WeChatResponse<object>> UpdateWeChatVersion(string version)
        {
            var requestBody = new WeChatRequest<WeChatVersion> { Type = 微信常量_接口请求.修改微信版本号,Data= new WeChatVersion { New=version } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }
        /// <inheritdoc/>
        public async Task<GetWeChatListResponse> GetWeChatListAsync()
        {
            var requestBody = new WeChatRequest<object>();
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<GetWeChatListResponse>(responseContent);
                return result ??new ();
            }
            return new ();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<QRCodeResult>> GetLoginQRCodeAsync()
        {
            var requestBody = new WeChatRequest<object>{ Type= 微信常量_接口请求.获取登录二维码 };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<QRCodeResult>>(responseContent);
                return result ?? new();
            }
            return new();
        }
        /// <inheritdoc/>
        public async Task<WeChatResponse<LoginResult>> GetLoginStatus()
        {
            var requestBody = new WeChatRequest<object>{ Type= 微信常量_接口请求.获取登录状态 };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<LoginResult>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<object>> SetDownloadImageTime(DownloadType downloadType=DownloadType.AllDayDownload)
        {
            var requestBody = new WeChatRequest<DownloadImageTimeData> { Type= 微信常量_接口请求.设置下载图片时间, Data=new DownloadImageTimeData { Type = downloadType } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<object>> KillWeChatProcess()
        {
            var requestBody = new WeChatRequest<object> { Type= 微信常量_接口请求.结束微信进程 };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }



        /// <summary>
        /// 异步解密 dat 图片。
        /// </summary>
        /// <param name="datPath">.dat 文件的完整路径。</param>
        /// <param name="savePath">解密后的图片保存路径。</param>
        /// <returns>返回解密操作的结果。</returns>
        /// <exception cref="ArgumentException"></exception>
        public async Task<WeChatResponse<object>> DecryptDatImageAsync(string datPath, string savePath)
        {
            if (string.IsNullOrEmpty(datPath))
            {
                throw new ArgumentException(".dat 文件路径不能为空。", nameof(datPath));
            }

            if (string.IsNullOrEmpty(savePath))
            {
                throw new ArgumentException("保存路径不能为空。", nameof(savePath));
            }

            var requestBody = new WeChatRequest<object> { Type=微信常量_接口请求.解密dat图片, Data = new {datPath,savePath}};
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<CheckWeChatResult>> CheckWeChatStatusAsync(string wxid)
        {
            var requestBody = new WeChatRequest<object> { Type = 微信常量_接口请求.微信状态检测};
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(wxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<CheckWeChatResult>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<byte[]> DownloadFileOrImageAsync(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return Array.Empty<byte>();
            }
            var response = await _httpClient.GetAsync($"{_baseUrl}/file?path={Uri.EscapeDataString(path)}");
            if (response.IsSuccessStatusCode)
            {
                var fileContent = await response.Content.ReadAsByteArrayAsync();
                //Console.WriteLine($"文件/图片下载成功，大小: {fileContent.Length} 字节");
                return fileContent;
            }
            return Array.Empty<byte>();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<object>> SendTextMessageAsync(string robotWxid, string recipientWxid, string message)
        {
            var requestBody = new WeChatRequest<TextMessageRequest> { Type = 微信常量_接口请求.发送文本消息,Data=new TextMessageRequest { Msg=message, Wxid=recipientWxid } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<object>> SendImageAsync(string robotWxid, string recipientWxid, string imagePath, string fileName = "")
        {
            var requestBody = new WeChatRequest<ImageOrFileMessageRequest> { Type = 微信常量_接口请求.发送图片, Data = new ImageOrFileMessageRequest { FileName = fileName,Path=imagePath ,Wxid = recipientWxid } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<object>> SendFileAsync(string robotWxid, string recipientWxid, string filePath, string fileName = "")
        {
            var requestBody = new WeChatRequest<ImageOrFileMessageRequest> { Type = 微信常量_接口请求.发送文件, Data = new ImageOrFileMessageRequest { FileName = fileName, Path = filePath, Wxid = recipientWxid } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<object>> SendDynamicEmojiAsync(string robotWxid, string recipientWxid, string path)
        {
            var requestBody = new WeChatRequest<ImageOrFileMessageRequest> { Type = 微信常量_接口请求.发送动态表情, Data = new ImageOrFileMessageRequest { FileName = null, Path = path, Wxid = recipientWxid } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<列表信息>> GetPersonalInfoAsync(string wxid)
        {
            var requestBody = new WeChatRequest<object> { Type = 微信常量_接口请求.获取个人信息, Data = new  { type="1" } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(wxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<列表信息>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<List<列表信息>>> GetFriendListAsync(string wxid)
        {
            var requestBody = new WeChatRequest<object> { Type = 微信常量_接口请求.获取好友列表, Data = new { type = "1" } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(wxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<List<列表信息>>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<List<列表信息>>> GetGroupChatListAsync(string wxid)
        {
            var requestBody = new WeChatRequest<object> { Type = 微信常量_接口请求.获取群聊列表, Data = new { type = "1" } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(wxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<List<列表信息>>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<List<列表信息>>> GetPublicAccountListAsync(string wxid)
        {
            var requestBody = new WeChatRequest<object> { Type = 微信常量_接口请求.获取公众号列表, Data = new { type = "1" } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(wxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<List<列表信息>>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<DeleteFriendResult>> DeleteFriendAsync(string robotWxid, string recipientWxid)
        {
            var requestBody = new WeChatRequest<object> { Type = 微信常量_接口请求.删除好友, Data = new  {Wxid = recipientWxid } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<DeleteFriendResult>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<object>> ModifyContactRemarkAsync(string robotWxid, string friendWxid, string newRemark)
        {
            var requestBody = new WeChatRequest<FriendRemarkRequest> { Type = 微信常量_接口请求.修改对象备注, Data = new FriendRemarkRequest { Wxid = friendWxid,Remark=newRemark } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<object>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<列表信息>> QueryContactInfoAsync(string robotWxid, string recipientWxid)
        {
            var requestBody = new WeChatRequest<ContactInfoRequest> { Type = 微信常量_接口请求.查询对象信息, Data = new ContactInfoRequest { Wxid = recipientWxid } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<列表信息>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<列表信息>> QueryGroupChatInfoAsync(string robotWxid, string recipientWxid)
        {
            var requestBody = new WeChatRequest<ContactInfoRequest> { Type = 微信常量_接口请求.查询群聊信息, Data = new ContactInfoRequest { Wxid = recipientWxid } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<列表信息>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<List<GroupMemberResult>>> GetGroupMemberListAsync(string robotWxid, string recipientWxid, string getNick = "2")
        {
            var requestBody = new WeChatRequest<ContactInfoRequest> { Type = 微信常量_接口请求.获取群成员列表, Data = new ContactInfoRequest { Wxid = recipientWxid,GetNick=getNick } };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<List<GroupMemberResult>>>(responseContent);
                return result ?? new();
            }
            return new();
        }

        /// <inheritdoc/>
        public async Task<WeChatResponse<GroupMemberResult>> GetGroupMemberNicknameAsync(string robotWxid, string groupWxid, string objWxid)
        {
            var requestBody = new WeChatRequest<GroupMemberNicknameRequest> { Type = 微信常量_接口请求.获取群成员昵称, Data = new GroupMemberNicknameRequest { Wxid = groupWxid,  ObjWxid=objWxid} };
            var jsonContent = JsonSerializer.Serialize(requestBody, options);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_baseUrl}?safekey={Uri.EscapeDataString(safekey)}&wxid={Uri.EscapeDataString(robotWxid)}", content);
            if (response.IsSuccessStatusCode)
            {
                // 获取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<WeChatResponse<GroupMemberResult>>(responseContent);
                return result ?? new();
            }
            return new();
        }
    }
}
